from urllib import parse

from django.db.models import Q
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.
from visitApi.ext.StandardResultsSetPagination import StandardResultsSetPagination
from visitApi.models import User, Announcement, Task, Info, Visit, Interview, Customer
from visitApi.serializers.BannerSerializers import BannerSerializers
from visitApi.serializers.CustomerSerializers import CustomerSerializers
from visitApi.serializers.InfoSerializers import InfoSerializers
from visitApi.serializers.InterviewSerializers import SaveInterviewSerializers
from visitApi.serializers.TaskSerializers import TaskSerializers
from visitApi.serializers.UserSerializers import UserSerializers, SaveUserSerializers
from visitApi.serializers.VisitSerializers import VisitSerializers, SaveVisitSerializers
from visitApi.util import HttpCode


class Login(APIView):
    """
    登录
    """

    def post(self, request):
        params = request.data
        user_name = params.get('nickName')
        user_pwd = params.get('password')
        if user_name is None or user_pwd is None:
            return Response({'code': HttpCode.FAIL, 'message': '参数缺省!'})
        else:
            try:
                user = User.objects.get(nickName=user_name, password=user_pwd)
                return Response(
                    {'code': HttpCode.SUCCESS, 'message': '登录成功',
                     'data': UserSerializers(user, many=False, ).data})
            except Exception as e:
                print(e.args)
                return Response({'code': HttpCode.FAIL, 'message': '用户或密码错误!'})


class Register(APIView):
    """
    注册
    """

    def post(selfs, request):
        params = request.data
        user_name = params.get('nickName')
        phone_number = params.get('phoneNumber')
        try:
            user = SaveUserSerializers(data=params)
            if (user.is_valid(raise_exception=True)):
                res = User.objects.filter(Q(nickName=user_name) | Q(phoneNumber=phone_number))
                if res.count() != 0:
                    return Response({'code': HttpCode.FAIL, 'message': '此手机号或者用户名已被注册!'})
                else:
                    res = user.save()
                    return Response({'code': HttpCode.SUCCESS, 'message': '注册成功!',
                                     'data': UserSerializers(res, many=False, ).data})
            else:
                return Response({'code': HttpCode.FAIL, 'message': '参数无效!'})
        except Exception as e:
            print(e.args)
            return Response({'code': HttpCode.FAIL, 'message': e.args})


class BannerList(APIView):
    """
    Banner轮播图
    """

    def get(selfs, request):
        list = Announcement.objects.all()
        return Response(
            {'code': HttpCode.SUCCESS, 'message': "成功",
             'data': BannerSerializers(list, many=True).data})


class TaskList(APIView):

    def get(self, request):
        task_list_all = Task.objects.all()
        paginator = StandardResultsSetPagination()
        page_task_list = paginator.paginate_queryset(task_list_all, self.request, view=self)
        task_list_serializers = TaskSerializers(page_task_list, many=True)
        data = paginator.get_paginated_response(task_list_serializers.data)

        return Response(
            {'code': HttpCode.SUCCESS, 'message': "成功",
             'data': data.data})


class InfoList(APIView):

    def post(self, request):
        params = request.data
        type = 0 if params.get('type') is None else params.get('type')
        info_list_all = Info.objects.filter(type=type)
        paginator = StandardResultsSetPagination()
        page_info_list = paginator.paginate_queryset(info_list_all, self.request, view=self)
        info_list_serializers = InfoSerializers(page_info_list, many=True)
        data = paginator.get_paginated_response(info_list_serializers.data)

        return Response(
            {'code': HttpCode.SUCCESS, 'message': "成功",
             'data': data.data})


class HistoryVisitList(APIView):
    """
    历史巡店接口
    """

    def post(self, request):
        params = request.data
        keyword = params.get('keyword')
        user_id = params.get('userId')
        visit_list_all = Visit.objects.filter(user__userId=user_id)
        paginator = StandardResultsSetPagination()
        page_visit_list = paginator.paginate_queryset(visit_list_all, self.request, view=self)
        visit_list_serializers = VisitSerializers(page_visit_list, many=True)
        data = paginator.get_paginated_response(visit_list_serializers.data)
        return Response(
            {'code': HttpCode.SUCCESS, 'message': "成功",
             'data': data.data})


class Visitupload(APIView):
    """
    巡店数据提交接口
    """

    def post(self, request):
        params = request.data
        try:
            visit = SaveVisitSerializers(data=params)
            if (visit.is_valid(raise_exception=True)):
                visit.save()
                return Response({'code': HttpCode.FAIL, 'message': "Success"})
            else:
                return Response({'code': HttpCode.FAIL, 'message': "提交失败!"})
        except Exception as e:
            print(e.args)
            return Response({'code': HttpCode.FAIL, 'message': e.args})


class HistoryInterviewList(APIView):
    def post(self, request):
        params = request.data
        user_id = params.get('userId')
        interview_list_all = Interview.objects.filter(user__userId=user_id)
        paginator = StandardResultsSetPagination()
        page_interview_list = paginator.paginate_queryset(interview_list_all, self.request, view=self)
        interview_list_serializers = VisitSerializers(page_interview_list, many=True)
        data = paginator.get_paginated_response(interview_list_serializers.data)
        return Response(
            {'code': HttpCode.SUCCESS, 'message': "成功",
             'data': data.data})


class InterviewSubmit(APIView):
    def post(self, request):
        params = request.data
        try:
            interview = SaveInterviewSerializers(data=params)
            if (interview.is_valid(raise_exception=True)):
                interview.save()
                return Response({'code': HttpCode.FAIL, 'message': "Success"})
            else:
                return Response({'code': HttpCode.FAIL, 'message': "提交失败!"})
        except Exception as e:
            print(e.args)
            return Response({'code': HttpCode.FAIL, 'message': e.args})


class CustomerList(APIView):
    """
    客户列表
    """
    def get(self,request):
      customer_list=  Customer.objects.all()
      return Response(
          {'code': HttpCode.SUCCESS, 'message': "成功",
           'data': CustomerSerializers(customer_list, many=True).data})